import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 284. 顶端迭代器
 * https://leetcode-cn.com/problems/peeking-iterator/
 */
public class Solutions_284 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3);
        Iterator<Integer> iterator = list.iterator();
        PeekingIterator obj = new PeekingIterator(iterator);
        int res1 = obj.next();  // output: 1
        System.out.println(res1);
        int res2 = obj.peek();  // output: 2
        System.out.println(res2);
        int res3 = obj.next();  // output: 2
        System.out.println(res3);
        int res4 = obj.next();  // output: 3
        System.out.println(res4);
        boolean res5 = obj.hasNext();  // output: false
        System.out.println(res5);
    }
}

class PeekingIterator implements Iterator<Integer> {
    Iterator<Integer> it = null;
    // 保存的总是 next() 返回的结果
    Integer cache = null;

    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        it = iterator;
        cache = it.hasNext() ? it.next() : null;
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return cache;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if (!hasNext()) {
            return null;
        }
        // 存在迭代的结果
        int res = cache.intValue();
        // 再次缓存 next() 元素
        cache = it.hasNext() ? it.next() : null;
        return res;
    }

    @Override
    public boolean hasNext() {
        return cache != null;
    }
}
